package cn.powerone.scm.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import cn.powerone.common.utils.DateUtils;
import cn.powerone.scm.domain.*;
import cn.powerone.scm.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

import cn.powerone.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import cn.powerone.scm.mapper.ScmSupplierOrdersMapper;

/**
 * 供应商订单Service业务层处理
 * 
 * @author PowerOne
 * @date 2025-07-04
 */
@Service
public class ScmSupplierOrdersServiceImpl implements IScmSupplierOrdersService 
{
    @Autowired
    private ScmSupplierOrdersMapper scmSupplierOrdersMapper;
    @Autowired
    private IScmCustomerOrdersService scmCustomerOrdersService;
    @Autowired
    private IScmSupplierOrderItemsService scmSupplierOrderItemsService;

    @Autowired
    private IScmMyCompanyInfoService scmMyCompanyInfoService;

    @Autowired
    private IScmSequenceParmService scmSequenceParmService;

    @Autowired
    private IScmSupplierService scmSupplierService;

    @Autowired
    private IScmSupplierQuotesService scmSupplierQuotesService;
    /**
     * 查询供应商订单
     * 
     * @param id 供应商订单主键
     * @return 供应商订单
     */
    @Override
    public ScmSupplierOrders selectScmSupplierOrdersById(Long id)
    {
        return scmSupplierOrdersMapper.selectScmSupplierOrdersById(id);
    }

    /**
     * 查询供应商订单列表
     * 
     * @param scmSupplierOrders 供应商订单
     * @return 供应商订单
     */
    @Override
    public List<ScmSupplierOrders> selectScmSupplierOrdersList(ScmSupplierOrders scmSupplierOrders)
    {
        return scmSupplierOrdersMapper.selectScmSupplierOrdersList(scmSupplierOrders);
    }

    /**
     * 新增供应商订单
     * 
     * @param scmSupplierOrders 供应商订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertScmSupplierOrders(ScmSupplierOrders scmSupplierOrders)
    {
        scmSupplierOrders.setCreateTime(DateUtils.getNowDate());
        int rows = scmSupplierOrdersMapper.insertScmSupplierOrders(scmSupplierOrders);
        insertScmSupplierOrderItems(scmSupplierOrders);
        return rows;
    }

    /**
     * 修改供应商订单
     * 
     * @param scmSupplierOrders 供应商订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateScmSupplierOrders(ScmSupplierOrders scmSupplierOrders) {
        BigDecimal totalAmount = BigDecimal.valueOf(0);
        for (ScmSupplierOrderItems item : scmSupplierOrders.getScmSupplierOrderItemsList()){
            if (item.getQuantity().compareTo(BigDecimal.ZERO) > 0) {
                totalAmount = totalAmount.add(item.getAmount()).add(item.getMoldCost()).add(item.getJigCost());
            }
        }
        scmSupplierOrders.setTotalAmount(totalAmount);
        scmSupplierOrders.setUpdateTime(DateUtils.getNowDate());
        scmSupplierOrdersMapper.deleteScmSupplierOrderItemsByOrderId(scmSupplierOrders.getId());
        insertScmSupplierOrderItems(scmSupplierOrders);
        return scmSupplierOrdersMapper.updateScmSupplierOrders(scmSupplierOrders);
    }

    /**
     * 批量删除供应商订单
     * 
     * @param ids 需要删除的供应商订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmSupplierOrdersByIds(Long[] ids)
    {
        scmSupplierOrdersMapper.deleteScmSupplierOrderItemsByOrderIds(ids);
        return scmSupplierOrdersMapper.deleteScmSupplierOrdersByIds(ids);
    }

    /**
     * 删除供应商订单信息
     * 
     * @param id 供应商订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmSupplierOrdersById(Long id)
    {
        scmSupplierOrdersMapper.deleteScmSupplierOrderItemsByOrderId(id);
        return scmSupplierOrdersMapper.deleteScmSupplierOrdersById(id);
    }

    /**
     * 新增供应商订单明细信息
     * 
     * @param scmSupplierOrders 供应商订单对象
     */
    public void insertScmSupplierOrderItems(ScmSupplierOrders scmSupplierOrders)
    {
        List<ScmSupplierOrderItems> scmSupplierOrderItemsList = scmSupplierOrders.getScmSupplierOrderItemsList();
        Long id = scmSupplierOrders.getId();
        if (StringUtils.isNotNull(scmSupplierOrderItemsList))
        {
            List<ScmSupplierOrderItems> list = new ArrayList<ScmSupplierOrderItems>();
            for (ScmSupplierOrderItems scmSupplierOrderItems : scmSupplierOrderItemsList)
            {
                scmSupplierOrderItems.setOrderId(id);

                list.add(scmSupplierOrderItems);
            }
            if (list.size() > 0)
            {
                scmSupplierOrdersMapper.batchScmSupplierOrderItems(list);
            }
        }
    }

    /**
     * 创建供应商订单
     *
     * @param scmCustomerOrders 客户订单对象
     * @return 结果
     */
    @Override
    public int createScmSupplierOrders(ScmCustomerOrders scmCustomerOrders) {
        if (scmCustomerOrders == null || scmCustomerOrders.getId() <= 0){
            return 0;
        }
        //查询客户订单明细
        ScmCustomerOrders customerOrder = scmCustomerOrdersService.selectScmCustomerOrdersById(scmCustomerOrders.getId());
        //创建供应商和供应商对应的供应商订单 mapping
        ConcurrentHashMap<Long, Long> supplierMap = new ConcurrentHashMap<>();
        ConcurrentHashMap<Long, BigDecimal> supplierOrderAmountMap = new ConcurrentHashMap<>();
//        ConcurrentHashMap<Long, Date> supplierRequestedDeliveryMap = new ConcurrentHashMap<>();
//        ConcurrentHashMap<Long, Date> supplierRepliedDeliveryMap = new ConcurrentHashMap<>();
        Long idOfSupplierOrder = null;
        int rows = 0;
        ScmSupplierOrders scmSupplierOrders;
        ScmSupplierOrderItems scmSupplierOrderItems;

        ScmMyCompanyInfo scmMyCompanyInfo = scmMyCompanyInfoService.selectScmMyCompanyInfoList(null).get(0);
        ScmSupplier scmSupplier = null;
        ScmSupplierQuotes scmSupplierQuotes = null;
        BigDecimal totalAmount = BigDecimal.valueOf(0);

        //遍历客户订单明细
        for (ScmCustomerOrderItems item : customerOrder.getScmCustomerOrderItemsList()){
            idOfSupplierOrder = supplierMap.get(item.getSupplierId());
            //如果不存在，则创建订单，组装供应商订单信息并插入供应商订单表
            if ( idOfSupplierOrder == null) {
                scmSupplier = scmSupplierService.selectScmSupplierById(item.getSupplierId());
                scmSupplierOrders = new ScmSupplierOrders();
                scmSupplierOrders.setProjectId(customerOrder.getProjectId());
                scmSupplierOrders.setOrderCode(scmSequenceParmService.generateScmSequence("supp_order_code"));
                scmSupplierOrders.setOrderDate(DateUtils.getNowDate());
                scmSupplierOrders.setRequestedDeliveryDate(customerOrder.getRequestedDeliveryDate());
                scmSupplierOrders.setRepliedDeliveryDate(customerOrder.getRepliedDeliveryDate());
                scmSupplierOrders.setTotalAmount(BigDecimal.valueOf(0));
                scmSupplierOrders.setPayedAmount(BigDecimal.valueOf(0));
                scmSupplierOrders.setPaymentStatus(1L);
                // 添加:设置发票金额为0
                scmSupplierOrders.setInvoiceAmount(BigDecimal.valueOf(0));
                scmSupplierOrders.setBuyerTitle(scmMyCompanyInfo.getName());
                scmSupplierOrders.setBuyerAddress( scmMyCompanyInfo.getAddress());
                scmSupplierOrders.setBuyerPerson( scmMyCompanyInfo.getContactName());
                scmSupplierOrders.setBuyerPhone( scmMyCompanyInfo.getPhone());
                scmSupplierOrders.setBuyerAccountBank( scmMyCompanyInfo.getBankName());
                scmSupplierOrders.setBuyerAccountNumber( scmMyCompanyInfo.getBankAccount());
                scmSupplierOrders.setBuyerSignDate(DateUtils.getNowDate());
                scmSupplierOrders.setSupplierId(scmSupplier.getId());
                scmSupplierOrders.setSellerTitle(scmSupplier.getName());
                scmSupplierOrders.setSellerAddress( scmSupplier.getAddress());
                scmSupplierOrders.setSellerPerson(scmSupplier.getLegalPerson());
                scmSupplierOrders.setSellerPhone( scmSupplier.getTelephone());
                scmSupplierOrders.setSellerAccountBank( scmSupplier.getBankName());
                scmSupplierOrders.setSellerAccountNumber( scmSupplier.getBankAccount());
                scmSupplierOrders.setSellerSignDate(DateUtils.getNowDate());
                rows += scmSupplierOrdersMapper.insertScmSupplierOrders(scmSupplierOrders);
                idOfSupplierOrder = scmSupplierOrders.getId();
                supplierMap.put(item.getSupplierId(), idOfSupplierOrder);
                supplierOrderAmountMap.put(idOfSupplierOrder, BigDecimal.ZERO);
//                supplierRequestedDeliveryMap.put(idOfSupplierOrder, customerOrder.getRequestedDeliveryDate());
//                supplierRepliedDeliveryMap.put(idOfSupplierOrder, customerOrder.getRepliedDeliveryDate());
            };
            //如果存在供应商订单，则组装供应商订单信息并插入供应商订单表
            scmSupplierOrderItems = new ScmSupplierOrderItems();
            scmSupplierOrderItems.setOrderId(idOfSupplierOrder);
            scmSupplierOrderItems.setProductId(item.getProductId());
            scmSupplierOrderItems.setProjectProductId(item.getProjectProductId());
            scmSupplierOrderItems.setCustomerQuoteId(item.getCustomerQuoteId());
            scmSupplierOrderItems.setSupplierId(item.getSupplierId());
            scmSupplierOrderItems.setSupplierQuoteId(item.getSupplierQuoteId());
            scmSupplierOrderItems.setSupplierName(item.getSupplierName());
            scmSupplierOrderItems.setPurchaseCategory(item.getPurchaseCategory());
            scmSupplierOrderItems.setDemandType(item.getDemandType());
            scmSupplierOrderItems.setModel(item.getModel());
            scmSupplierOrderItems.setManufactureNumber(item.getManufactureNumber());
            scmSupplierOrderItems.setManufactureSubNumber(item.getManufactureSubNumber());
            scmSupplierOrderItems.setDrawingNumberModel(item.getDrawingNumberModel());
            scmSupplierOrderItems.setDrawingVersion(item.getDrawingVersion());
            scmSupplierOrderItems.setProductName(item.getProductName());
            scmSupplierOrderItems.setMaterial(item.getMaterial());
            scmSupplierOrderItems.setSize(item.getSize());
            scmSupplierOrderItems.setSpecification(item.getSpecification());
            scmSupplierOrderItems.setColor(item.getColor());
            scmSupplierOrderItems.setUnitPriceType(item.getUnitPriceType());
//            scmSupplierOrderItems.setUnitPrice(item.getUnitPrice());
            //单价从供应商报价单中获取
            scmSupplierQuotes = scmSupplierQuotesService.selectScmSupplierQuotesById(item.getSupplierQuoteId());
            if (item.getUnitPriceType() == 1 ||  item.getUnitPriceType() == 2){
                scmSupplierOrderItems.setUnitPrice(scmSupplierQuotes.getDisposableUnitPrice());
            }else if (item.getUnitPriceType() == 3){
                scmSupplierOrderItems.setUnitPrice(scmSupplierQuotes.getTryUnitPrice());
            }else if (item.getUnitPriceType() == 4){
                scmSupplierOrderItems.setUnitPrice(scmSupplierQuotes.getMassUnitPrice());
            }else {
                scmSupplierOrderItems.setUnitPrice(BigDecimal.ZERO);
            }
            scmSupplierOrderItems.setQuantity(item.getQuantity());
            scmSupplierOrderItems.setAmount(scmSupplierOrderItems.getUnitPrice().multiply(scmSupplierOrderItems.getQuantity()));
            scmSupplierOrderItems.setMoldCost(item.getMoldCost());
            scmSupplierOrderItems.setJigCost(item.getJigCost());
            scmSupplierOrderItems.setRequestedDeliveryDate(item.getRequestedDeliveryDate());
            scmSupplierOrderItems.setRepliedDeliveryDate(item.getRepliedDeliveryDate());
            scmSupplierOrderItemsService.insertScmSupplierOrderItems(scmSupplierOrderItems);
            if (scmSupplierOrderItems.getQuantity().compareTo(BigDecimal.ZERO) > 0){
                totalAmount = supplierOrderAmountMap.get(idOfSupplierOrder).add(scmSupplierOrderItems.getAmount()).add(scmSupplierOrderItems.getMoldCost()).add(scmSupplierOrderItems.getJigCost());
                supplierOrderAmountMap.put(idOfSupplierOrder, totalAmount);
            }
        }
        for (Long idOfSupplierOrderTemp : supplierOrderAmountMap.keySet()){
            scmSupplierOrders = new ScmSupplierOrders();
            scmSupplierOrders.setId(idOfSupplierOrderTemp);
            scmSupplierOrders.setTotalAmount(supplierOrderAmountMap.get(idOfSupplierOrderTemp));
            // 添加:同步更新发票金额
//            scmSupplierOrders.setInvoiceAmount(supplierOrderAmountMap.get(idOfSupplierOrderTemp));
            scmSupplierOrdersMapper.updateScmSupplierOrders(scmSupplierOrders);
        }

        return rows;
    }

    @Override
    public int selectSupplierOrderCountByMonth(Date yesterday) {
        return scmSupplierOrdersMapper.selectSupplierOrderCountByMonth(yesterday);
    }

    @Override
    public int selectSupplierOrderCountByYear(Date yesterday) {
        return scmSupplierOrdersMapper.selectSupplierOrderCountByYear(yesterday);
    }

    @Override
    public int selectSupplierOrderCountAll() {
        return scmSupplierOrdersMapper.selectSupplierOrderCountAll();
    }
}
